package cAmqp

import (
	"fmt"
	"runtime"

	"github.com/gin-gonic/gin"
	"github.com/rabbitmq/amqp091-go"

	"gitee.com/csingo/cLog"
)

func traces() []string {
	var count = 1
	var result = []string{}
	for {
		_, file, line, ok := runtime.Caller(count)
		if !ok {
			break
		}
		result = append(result, fmt.Sprintf("%s:%d\n", file, line))
		count++
	}

	return result
}

func defaultHandler(ctx *gin.Context, delivery []amqp091.Delivery) {
	for _, item := range delivery {
		_ = item.Ack(false)
	}
}

func runBindHandlerFunc(ctx *gin.Context, status bool, params amqp091.Table, handler BindHandlerFunc) {
	defer func() {
		if r := recover(); r != nil {
			cLog.WithContext(ctx, map[string]any{
				"source": "cAmqp.runParamsAssertHandler",
				"traces": traces(),
				"panic":  fmt.Sprintf("%v", r),
			}).Error("AMQP 消费者执行断言失败")
		}
	}()

	handler(ctx, status, params)
}

func runParamsHandlerFunc(ctx *gin.Context, params amqp091.Table, handler ParamsHandlerFunc) error {
	defer func() {
		if r := recover(); r != nil {
			cLog.WithContext(ctx, map[string]any{
				"source": "cAmqp.runParamsAssertHandler",
				"traces": traces(),
				"panic":  fmt.Sprintf("%v", r),
			}).Error("AMQP 消费者执行断言失败")
		}
	}()

	return handler(ctx, params)
}

func runMessageHandlerFunc(ctx *gin.Context, msgs *[]amqp091.Delivery, autoAck bool, driver *AmqpConf_Driver, handler MessageHandlerFunc) {
	defer func() {
		if r := recover(); r != nil {
			cLog.WithContext(ctx, map[string]any{
				"source": "cAmqp.runParamsAssertHandler",
				"traces": traces(),
				"panic":  fmt.Sprintf("%v", r),
			}).Error("AMQP 消费者执行断言失败")
		}
	}()

	data := []amqp091.Delivery{}

	for _, msg := range *msgs {
		data = append(data, msg)
		if autoAck {
			e := msg.Ack(false)
			if e != nil {
				cLog.WithContext(ctx, map[string]any{
					"source":   "cAmqp.runParamsAssertHandler",
					"exchange": driver.ExchangeName,
					"type":     driver.ExchangeType,
					"route":    driver.RoutingKey,
					"queue":    driver.QueueName,
					"err":      e.Error(),
				}).Error("AMQP 消费者ack异常(ServerPush)")
			}
		}
	}
	*msgs = (*msgs)[0:0]

	handler(ctx, data)
}
